package com.starchen.optimalselection.web.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starchen.optimalselection.common.exception.CustomException;
import com.starchen.optimalselection.common.utils.ResponseEnum;
import com.starchen.optimalselection.config.JwtTokenUtil;
import com.starchen.optimalselection.web.mapper.MemberMapper;
import com.starchen.optimalselection.web.model.Member;
import com.starchen.optimalselection.web.model.vo.MemberVo;
import com.starchen.optimalselection.web.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


@Slf4j
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private WxMaService wxMaService;
    
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    //微信小程序登录接口
    @Override
    public String login(String code) {
        //1 获取code值，使用微信工具包对象，获取微信唯一标识openid
        String openid = null;
        try {
            WxMaJscode2SessionResult sessionInfo =
                    wxMaService.getUserService().getSessionInfo(code);
            openid = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

        //2 根据openid查询数据库表，判断是否第一次登录
        //如果openid不存在返回null，如果存在返回一条记录
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getWxOpenId,openid);
        Member customerInfo = memberMapper.selectOne(wrapper);

        //3 如果第一次登录，添加信息到用户表
        if(customerInfo == null) {
            customerInfo = new Member();
            customerInfo.setNickName(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfo.setWxOpenId(openid);
            memberMapper.insert(customerInfo);
        }

        String token = jwtTokenUtil.generateToken(customerInfo.getId().toString());

        return token;
    }

    //获取客户登录信息
    @Override
    public MemberVo getUserInfo(String token) {
        //2 根据token查询redis
        //3 查询token在redis里面对应用户id
        //String customerId = (String)redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        String customerId = jwtTokenUtil.getUserNameFromToken(token);

        if(!StringUtils.hasText(customerId)) {
            throw new CustomException(ResponseEnum.DATA_ERROR);
        }

        //1 根据用户id查询用户信息
        Member customerInfo = memberMapper.selectById(customerId);

        //2 封装到CustomerLoginVo
        MemberVo customerLoginVo = new MemberVo();
        BeanUtils.copyProperties(customerInfo,customerLoginVo);

        String phone = customerInfo.getPhone();
        boolean isBindPhone = StringUtils.hasText(phone);
        customerLoginVo.setIsBindPhone(isBindPhone);

        return customerLoginVo;
    }

        /*
    ////更新客户微信手机号码
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        //1 根据code值获取微信绑定手机号码
        try {
            WxMaPhoneNumberInfo phoneNoInfo =
                    wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
            String phoneNumber = phoneNoInfo.getPhoneNumber();

            //更新用户信息
            Long customerId = updateWxPhoneForm.getCustomerId();
            CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
            customerInfo.setPhone(phoneNumber);
            customerInfoMapper.updateById(customerInfo);

            return true;
        } catch (WxErrorException e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public String getCustomerOpenId(Long customerId) {
        LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerInfo::getId,customerId);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(wrapper);
        return customerInfo.getWxOpenId();
    }

     */

}
